//
// Original code taken from Andy Pennell's blog at 
// http://blogs.msdn.com/b/andypennell/archive/2010/11/01/error-reporting-on-windows-phone-7.aspx
//

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;

namespace EmperialApps.WeatherSpark.Agent.Helpers {

    internal static class LittleWatsonAgent {

        private const string FileName = SharedStorage.ErrorFile;
        private const string Separator = "----------------------------------------";

        internal static void RecordException( Exception ex, string header, string footer, IEnumerable<string> log ) {
            try {
                using( var store = IsolatedStorageFile.GetUserStoreForApplication( ) ) {
                    SafeDeleteFile( store );
                    using( TextWriter output = new StreamWriter( store.CreateFile( FileName ) ) ) {
                        output.WriteLine( header );

                        string exceptionType = ex.GetType( ).Name;
                        if( !ex.Message.Contains( exceptionType ) )
                            output.Write( "[{0}] ", exceptionType );
                        output.WriteLine( ex.Message );

                        output.WriteLine( ex.StackTrace );

                        output.WriteLine( Separator );
                        output.WriteLine( footer );

                        output.WriteLine( Separator );
                        foreach( string line in log )
                            output.WriteLine( line );
                    }
                }
            }
            catch( Exception ) { }
        }

        private static void SafeDeleteFile( IsolatedStorageFile store ) {
            try {
                store.DeleteFile( FileName );
            }
            catch( Exception ) { }
        }

    }

}
